<template>
  <d2-container>

    <template slot="header">
      <el-form :gutter="24" ref="search-box" :model="mainQuery" label-position="left" :inline="true" label-width="110px" v-show="showSearchBox">
            <el-form-item label="商户号：" size="mini">
              <el-input placeholder="" v-model="mainQuery.mchNo" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>

            <el-form-item label="平台订单号：" size="mini">
              <el-input placeholder="" v-model="mainQuery.tradeNo" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>
            <el-form-item label="商户订单号：" size="mini">
              <el-input placeholder="" v-model="mainQuery.attach" @keyup.enter.native="handleSearch" size="small" clearable></el-input>
            </el-form-item>

            <el-form-item label="退款状态：" size="mini">
              <el-select v-model="mainQuery.isRefund" size="small" clearable>
                <el-option v-for="item in isRefundOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="拒付状态：" size="mini">
              <el-select v-model="mainQuery.isDis" size="small" clearable>
                <el-option v-for="item in isDisOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="冻结状态：" size="mini">
              <el-select v-model="mainQuery.isFrozen" size="small" clearable>
                <el-option v-for="item in isFrozenOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="解冻状态：" size="mini">
              <el-select v-model="mainQuery.isThaw" size="small" clearable>
                <el-option v-for="item in isThawOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

        <el-form-item label="时间区间：" size="mini">
          <el-date-picker size="small" v-model="dateTimeRange" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="datetimePickerOptions" @change="onDateTimePickerChange" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div class="search-btn-box">
        <div class="right">
          <el-button class="filter-item" icon="el-icon-download" size="mini" @click="handleExportExcel">导出</el-button>
          <el-button class="filter-item" icon="" type="default" @click="resetMainData" :loading="mainTable.loading" size="mini">重置</el-button>
          <el-button class="filter-item" icon="el-icon-search" type="primary" @click="handleSearch" :loading="mainTable.loading" size="mini">查询</el-button>
        </div>
        <el-link type="primary" @click="showSearchBox = !showSearchBox">{{ showSearchBox ? '收起' : '展开' }}</el-link>
      </div>
    </template>

    <!--主列表数据-->
    <d2-crud ref="d2Crud" selection-row :options="mainTable.options" :index-row="mainTable.indexRow" :columns="mainTable.columns" :data="mainTable.list" :loading="mainTable.loading" @current-change="onMainCurrentChange" @row-dblclick="onMainDoubleClick" @custom-emit-handle-order="handleOrderDetail" @custom-emit-handle-email="handleEmail" @selection-change="onMainSelectionChange"></d2-crud>

    <template slot="footer">
      <el-pagination @size-change="handleMainSizeChange" @current-change="handleMainPageChange" :current-page="mainTable.pagination.currentPage" :page-sizes="mainTable.pagination.pageSizes" :page-size="mainTable.pagination.pageSize" :page-count="mainTable.pagination.pageCount" :total="mainTable.pagination.total" layout="total, sizes, prev, pager, next, jumper" :background="true">
      </el-pagination>
    </template>

    <dialog-detail ref="dialog-detail" @dialog-close="fetchMainData"></dialog-detail>

    <dialog-email ref="dialog-email" @dialog-close="fetchMainData"></dialog-email>

    <common-export ref="common-export"></common-export>

  </d2-container>
</template>

<script>

import ApiMain from '@/api/trade.detail';
import DialogAdd from './dialog-add';
import CommonExport from '../../common/export';
import DialogEmail from './dialog-email';
import util from '@/libs/util.js';
import ChannelApiMain from '@/api/bank.channel';
import HandSettleApiMain from '@/api/trade.hand';
import { transStatusOptions, isCheckedOptions, isRefundOptions, isFrozenOptions, isShipOptions, isDisOptions, isThawOptions, isTestOptions, needHandSettleOptions } from '@/const/constant';
import DatetimePickerMixin from '@/mixin/DatetimePickerMixin';

var isSettleOptions = [
  {value: 0, label: '未结算'},
  {value: 1, label: '待审核'},
  {value: 2, label: '已结算'},
];

let channelTypeList = {
  "1": '储蓄卡',
  "2": "信用卡",
  "3": "支付宝",
  "4": "微信"
}

export default {
  name: 'trade-detail',
  mixins: [
    DatetimePickerMixin,
  ],
  components: {
    'dialog-detail': DialogAdd,
    'dialog-email': DialogEmail,
    'common-export': CommonExport,
  },
  data() {
    return {

      mainQueryRaw: null,
      mainQuery: {
        mchNo: '',
        // terNo: '',
        tradeNo: '',
        isRefund: '',
        // isChecked: '',
        isSettle: 2,
        isShip: '',
        isDis: '',
        isFrozen: '',
        isThaw: '',
        channelId: '',
        cardType: '',
        transStatus: '',
        cardEmail: '',
        cardFullName: '',
        cardFullPhone: '',
        ipAddress: '',
        needHandSettle: '',
        startTime: '',
        endTime: ''
      },

      mainTable: {
        loading: false,
        options: {
          border: true,
          stripe: true,
          highlightCurrentRow: true,
          emptyText: '暂无数据',
          size: 'mini',
        },
        // indexRow: {
        //   title:'序号',
        //   width: "80",
        //   align:'center'
        // },
        indexRow: null,
        allowSelect: false,
        columns: [
          { title: '销售员', key: 'salesName', align: 'center', width: '120', showOverflowTooltip: true},
          { title: '平台订单号', key: 'tradeNo', align: 'center', width: '180', showOverflowTooltip: true, },
          { title: '商户订单号', key: 'orderNo', align: 'center', width: '180', showOverflowTooltip: true },
          { title: '商户号', key: 'mchNo', align: 'center', width: '120', showOverflowTooltip: true },
          { title: '交易时间', key: 'createTime', align: 'center', width: '180', showOverflowTooltip: true },
          {
            title: '交易金额', key: 'mchTransAmount', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
              return row.mchTransCurrency + ' ' + row.mchTransAmount / 100
            }
          },
          { title: '交易状态', key: 'strTransStatus', align: 'center', width: '120', showOverflowTooltip: true },
          {
            title: '商户结算金额', key: 'settleAmount', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
              return row.settleCurrency + ' ' + row.settleAmount / 100
            }
          },
              {title: '手续费', key: 'serviceFee', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
            return  row.serviceFee / 100
          }},
          { title: '交易网址', key: 'mchUrl', align: 'center', width: '120', showOverflowTooltip: true },
          {
            title: '交易方式', key: 'channelType', align: 'center', width: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
              return channelTypeList[cellValue]
            }
          },
          { title: '交易通道', key: 'channelName', align: 'center', width: '180', showOverflowTooltip: true },
        ],
        rowHandle: {
          // width: '250',
          // align: 'center',
          // fixed: 'right',
          // custom: [
          //   {
          //     text: '查看订单',
          //     type: 'primary',
          //     size: 'mini',
          //     emit: 'custom-emit-handle-order'
          //   },
          //   {
          //     text: '邮箱发送详情',
          //     type: 'default',
          //     size: 'mini',
          //     emit: 'custom-emit-handle-email'
          //   }
          // ]
        },
        list: [],
        pagination: {
          currentPage: 1,
          pageSize: 50,
          total: 0,
          pageSizes: [50, 100, 200]
        },
        selectionRow: [],
      },
      // 1 渠道类型 1.储蓄卡 2.信用卡 3.支付宝 4.微信 

      transStatusOptions: transStatusOptions,
      isCheckedOptions: isCheckedOptions,
      isRefundOptions: isRefundOptions,
      isFrozenOptions: isFrozenOptions,
      isShipOptions: isShipOptions,
      isSettleOptions: isSettleOptions,
      isDisOptions: isDisOptions,
      isThawOptions: isThawOptions,
      isTestOptions: isTestOptions,
      needHandSettleOptions: needHandSettleOptions,
      channelIdOptions: [],
      dateTimeRange: [],
      showSearchBox: true,
      fullLoading: true,
      tExportLog: null,
    }
  },
  mounted() {
    this.mainQueryRaw = Object.copy(this.mainQuery);

    this.fetchChannelOptions();
    this.resetMainData();
  },
  beforeDestroy() {
  },
  methods: {

    handleSearch() {
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData();
    },

    renderMainData(re) {
      this.mainTable.list = re.list;
      this.mainTable.pagination.total = re.total;
    },

    handleMainSizeChange(val) {
      this.mainTable.pagination.pageSize = val;
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData()
    },
    handleMainPageChange(val) {
      this.mainTable.pagination.currentPage = val;
      this.fetchMainData()
    },

    buildMainQuery() {

      var query = {
        page: this.mainTable.pagination.currentPage,
        limit: this.mainTable.pagination.pageSize,
        search: this.mainQuery,
      };

      // return query; 
      
      // 这里返回一个副本,避免在外部修改了原始变量
      return Object.copy(query);
    },

    resetMainData() {
      this.mainQuery = Object.copy(this.mainQueryRaw);
      this.dateTimeRange = [];
      this.fetchMainData();
    },

    fetchChannelOptions() {
      ChannelApiMain.option().then(re => {
        this.channelIdOptions = re;
      })
    },

    async fetchMainData() {

      this.mainTable.loading = true;

      try {
        var re = await ApiMain.list(this.buildMainQuery());
        this.renderMainData(re);
      } catch (err) { }

      this.mainTable.loading = false;

    },

    onDateTimePickerChange() {
      this.mainQuery.createTimeRange = this.dateTimeRange;
    },

    onMainCurrentChange(now, old) {
      this.mainTable.current = now;
    },

    onMainDoubleClick(now) {
      this.mainTable.current = now;
      this.$refs['dialog-detail'].show(now.id);
    },

    onMainSelectionChange(now, old) {
      this.mainTable.selectionRow = now
    },

    handleOrderDetail({ index, row }) {
      this.$refs['dialog-detail'].show(row.id);
    },

    handleEmail({ index, row }) {
      this.$refs['dialog-email'].show(row.id);
    },

    handleExportExcel() {
      this.$refs['common-export'].handleExportExcel(ApiMain, this.mainQuery);
    },

    // 手动结算
    handleHandSettle() {
      if (this.mainTable.selectionRow.length == 0) {
        this.$message({ message: '请选择行', type: 'error' });
        return;
      }

      // 检查是否符合条件
      let tradeNos = [];
      for (var i in this.mainTable.selectionRow) {
        if (this.mainTable.selectionRow[i].isSettle != 0) {
          this.$message({ message: '单号：' + this.mainTable.selectionRow[i].tradeNo + '结算状态不是未结算，不能操作', type: 'error' });
          return;
        }
        if (this.mainTable.selectionRow[i].currentTimeStamp - this.mainTable.selectionRow[i].createTimeStamp < this.mainTable.selectionRow[i].handSettleLimit) {
          this.$message({ message: '单号：' + this.mainTable.selectionRow[i].tradeNo + '不符合手工结算条件' + (this.mainTable.selectionRow[i].handSettleLimit / 24 / 3600) + '天', type: 'error' });
          return;
        }
        tradeNos.push(this.mainTable.selectionRow[i].tradeNo);
      }

      this.$confirm('确定对选中的订单进行手动结算操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doHandSettle(tradeNos.join(','))
      });
    },

    async doHandSettle(tradeNos) {
      await HandSettleApiMain.add({ tradeNos: tradeNos });
      this.$message({ message: '操作成功', type: 'success' });
      this.fetchMainData();
    },

  }
}
</script>

<style>
</style>
